﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using Common.Utilities;
using OnlineVideos.Data;
using InsertIntoDataBase;
using OnlineVideos.UI;
using PicasaMobileInterface;
using System.IO.IsolatedStorage;
using System.Threading;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using System.Windows.Controls.Primitives;
using Social_Celebrities.UserControls;

namespace Social_Celebrities.Views
{
    public partial class AddCast : PhoneApplicationPage
    {
        Help_Popup helppopup;
        Help_popup_Twitter helppopup_twit;
        Help_Popup_Blog helppopup_blog;
        string ImageUrl = string.Empty;
        AutoResetEvent auto = new AutoResetEvent(false);
        bool SamePage = false;
        TextBlock TbId = default(TextBlock);

        public AddCast()
        {
            InitializeComponent();
            helppopup = new Help_Popup();
            helppopup_twit = new Help_popup_Twitter();
            helppopup_blog = new Help_Popup_Blog();
            LoadAds();
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, AddcastAd, 2);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In AddCast.xaml.cs file file", ex);
                string excepmess = "Exception in LoadAds Method In AddCast.xaml.cs file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if(!string.IsNullOrEmpty(Constants.FacebookNID))
            TbFacebookID.Text = Constants.FacebookNID;
            if (!string.IsNullOrEmpty(Constants.TwitterScreenName))
            TbTwitterID.Text = Constants.TwitterScreenName;
            if (!string.IsNullOrEmpty(Constants.BlogAddress))
            TbBloggerID.Text = Constants.BlogAddress;
            if (Constants.editcelebrity == true && Constants.UserImage_socialcelebs == null)
            {
                int personid = Constants.personid;
                CastProfile cp = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == personid).FirstOrDefaultAsync()).Result;
                TbCelebrity.Text = cp.Name;
                List<Phone_SocialFeed> lps = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.PersonId == personid).ToListAsync()).Result;
                foreach (Phone_SocialFeed feed in lps)
                {
                    if (feed.FeedType.ToLower() == "facebook" && string.IsNullOrEmpty(Constants.FacebookNID))
                        TbFacebookID.Text = feed.FeedLink.Replace("https://www.facebook.com/feeds/page.php?id=", "").Replace("&format=rss20", "");
                    else if (feed.FeedType.ToLower() == "twitter" && string.IsNullOrEmpty(Constants.TwitterScreenName))
                        TbTwitterID.Text = feed.FeedLink;
                    else if(string.IsNullOrEmpty(Constants.BlogAddress))
                        TbBloggerID.Text = feed.FeedLink;
                }
                string imagename = personid + ".jpg" ;
                if (Task.Run(async () => await Storage.FileExists("/" + ResourceHelper.ProjectName + Constants.PersonImagePath + imagename)).Result)
                {
                    Constants.UIThread = true;
                    personlocalimg.Source = ResourceHelper.getpersonTileImage(imagename);
                    Constants.UIThread = false;
                }
                else if (!string.IsNullOrEmpty(cp.FlickrPersonImageUrl))
                {
                    personlocalimg.Source = new BitmapImage(new Uri(cp.FlickrPersonImageUrl,UriKind.Absolute));
                }
               
            }
            if (e.NavigationMode == NavigationMode.Back && !string.IsNullOrEmpty(Constants.SocialCelebrityId))
            {
                if (TbId != default(TextBlock))
                {
                    TbId.Text = Constants.SocialCelebrityId;
                    TbId = default(TextBlock);
                    Constants.SocialCelebrityId = string.Empty;
                }
            }
            if (e.NavigationMode == NavigationMode.Back && SamePage == false)
            {
                if (Constants.UserImage_socialcelebs != null)
                {
                    if (personlocalimg.Source == null)
                    {
                        personlocalimg.Source = Constants.UserImage_socialcelebs;
                        persononlineimg.Source = new BitmapImage(new Uri("/Images/peoplefromonline.png", UriKind.RelativeOrAbsolute));
                    }
                    else
                    {
                        persononlineimg.Source = Constants.UserImage_socialcelebs;
                        personlocalimg.Source = new BitmapImage(new Uri("/Images/peoplefromlocal.png", UriKind.RelativeOrAbsolute));
                    }
                }
                Constants.UserImage_socialcelebs = null;
            }
            else
                SamePage = false;
        }

        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                string personid = string.Empty;
                if (Constants.editcelebrity == true)
                {
                    personid = Constants.personid.ToString();
                }
                else
                {
                    if (Task.Run(async () => await Constants.connection.Table<CastProfile>().OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result != null)
                        personid = (Task.Run(async () => await Constants.connection.Table<CastProfile>().OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1).ToString();
                    else
                        personid = "1";
                }
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (isoStore.FileExists("/" + ResourceHelper.ProjectName + Constants.PersonImagePath + personid + ".jpg"))
                {
                    ImageUrl = string.Empty;
                    BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogType == "people").FirstOrDefaultAsync()).Result;
                    if (NetworkHelper.IsNetworkAvailableForDownloads())
                    {
                       PicasaInterface pi = new PicasaInterface(bt.BlogUserName, bt.BlogPassword);
                        uploadImage();
                    }
                }
                else
                {
                    ImageUrl = "http://t1.gstatic.com/images?q=tbn:ANd9GcQyJXo-3YWevA9tkGmycIy5hs1KTgonIT03l-iwKDj09_qLYbivzRgslxlK";
                }
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at bg_DoWork Method in AddCast.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at bg_DoWork method in AddCast.xaml.cs file", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }
        public void uploadImage()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://picasaweb.google.com/data/feed/api/user/" + CONST.USER);
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch)";
            request.Method = "POST";
            request.ContentType = "image/png";
            request.Headers["Authorization"] = CONST.PIC_AUTH + CONST.AUTH_Token;
            request.BeginGetRequestStream(new AsyncCallback(GetPicasaStreamCallback), request);
            auto.WaitOne();
        }

        private void GetPicasaStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                // OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                string personid = string.Empty;
                if (Constants.editcelebrity == true)
                {
                    personid = Constants.personid.ToString();
                }
                else
                {
                    if (Task.Run(async () => await Constants.connection.Table<CastProfile>().OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result != null)
                        personid = (Task.Run(async () => await Constants.connection.Table<CastProfile>().OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1).ToString();
                    else
                        personid = "1";
                }
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = isoStore.OpenFile("/" + ResourceHelper.ProjectName + Constants.PersonImagePath + personid + ".jpg", FileMode.Open,FileAccess.Read);
                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                byte[] buffer = new byte[fileStream.Length / 4];
                int bytesRead = -1;
                fileStream.Position = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                postStream.Close();
                isoStore.Dispose();
                request.BeginGetResponse(new AsyncCallback(RequestPicasaCompleted), request);
            }
            catch (Exception ex)
            {

                //Exceptions.SendErrortoMail("Exception at GetPicasaStreamCallback Method in AddCast.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at GetPicasaStreamCallback method in AddCast.xaml.cs file", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void RequestPicasaCompleted(IAsyncResult result)
        {
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(result);
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                XElement MyXMLConfig = XElement.Load(responseReader);
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                ImageUrl = MyXMLConfig.Descendants(atomNS + "content").Attributes().Where(i => i.Name == "src").FirstOrDefault().Value;
                auto.Set();
            }
            catch (Exception ex)
            {
            
                auto.Set();
                //Exceptions.SendErrortoMail("Exception at RequestPicasaCompleted Method in AddCast.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at RequestPicasaCompleted method in AddCast.xaml.cs file", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void btnsave_Click_1(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TbCelebrity.Text))
                valid.Visibility = Visibility.Visible;
            else
            {
                BackgroundWorker bg = new BackgroundWorker();
                bg.DoWork += bg_DoWork;
                bg.RunWorkerCompleted += bg_RunWorkerCompleted;
                bg.RunWorkerAsync();
            }
        }

        void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                IDictionary<string, TextBlock> TypeList = new Dictionary<string, TextBlock>();
                TypeList.Add("FaceBook", TbFacebookID);
                TypeList.Add("Twitter", TbTwitterID);
                TypeList.Add("Blog", TbBloggerID);
                if (Constants.editcelebrity == true)
                {
                    Constants.editcelebrity = false;
                    CastProfile cp = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == Constants.personid).FirstOrDefaultAsync()).Result;
                    int personid = cp.PersonID;
                    cp.Name = TbCelebrity.Text;
                    cp.FlickrPersonImageUrl = ImageUrl;
                    Constants.connection.UpdateAsync(cp);

                    List<Phone_SocialFeed> ps = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.PersonId == personid).ToListAsync()).Result;
                    List<Phone_SocialFeed> feedlist = new List<Phone_SocialFeed>();
                    foreach (Phone_SocialFeed ss in ps)
                    {
                        if (ss.FeedType.ToLower() == "facebook")
                        {
                            if (!string.IsNullOrEmpty(TbFacebookID.Text))
                                ss.FeedLink = "https://www.facebook.com/feeds/page.php?id=" + TbFacebookID.Text + "&format=rss20";
                        }
                        else if (ss.FeedType.ToLower() == "twitter")
                        {
                            if (!string.IsNullOrEmpty(TbTwitterID.Text))
                            {
                                if (TbTwitterID.Text.StartsWith("@"))
                                    ss.FeedLink = TbTwitterID.Text.Substring(1);
                                else
                                    ss.FeedLink = TbTwitterID.Text;
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(TbBloggerID.Text))
                            {
                                if (TbBloggerID.Text.Contains("http://") || TbBloggerID.Text.Contains("https://"))
                                    ss.FeedLink = TbBloggerID.Text;
                                else
                                    ss.FeedLink = "http://" + TbBloggerID.Text;
                            }
                        }                     
                        Constants.connection.UpdateAsync(ss);
                    }                 
                }
                else
                {
                    CastProfile cp = new CastProfile();
                    cp.PersonID = (Task.Run(async () => await Constants.connection.Table<CastProfile>().OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result == null) ? 1 : (Task.Run(async () => await Constants.connection.Table<CastProfile>().OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1);
                    cp.Name = TbCelebrity.Text;
                    cp.Description = string.Empty;
                    cp.GalleryImageCount = 0;
                    cp.FlickrPersonImageUrl = ImageUrl;
                    cp.FlickrPanoramaImageUrl = string.Empty;
                    cp.Rating = 4.0f;
                    Constants.connection.InsertAsync(cp);
                    foreach (KeyValuePair<string, TextBlock> k in TypeList)
                    {
                        Phone_SocialFeed ps = new Phone_SocialFeed();
                        ps.PersonId = Task.Run(async () => await Constants.connection.Table<CastProfile>().OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID;
                        ps.FeedType = k.Key.ToString();
                        if (k.Key.ToString() == "FaceBook")
                        {
                            if (!string.IsNullOrEmpty(((TextBlock)k.Value).Text))
                                ps.FeedLink = "https://www.facebook.com/feeds/page.php?id=" + ((TextBlock)k.Value).Text + "&format=rss20";
                        }
                        else if (k.Key.ToString() == "Twitter")
                        {
                            if (!string.IsNullOrEmpty(((TextBlock)k.Value).Text))
                            {
                                if (((TextBlock)k.Value).Text.StartsWith("@"))
                                    ps.FeedLink = ((TextBlock)k.Value).Text.Substring(1);
                                else
                                    ps.FeedLink = ((TextBlock)k.Value).Text;
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(((TextBlock)k.Value).Text))
                            {
                                if (((TextBlock)k.Value).Text.Contains("http://") || ((TextBlock)k.Value).Text.Contains("https://"))
                                    ps.FeedLink = ((TextBlock)k.Value).Text;
                                else
                                    ps.FeedLink = "http://" + ((TextBlock)k.Value).Text;
                            }
                        }
                        Constants.connection.InsertAsync(ps);
                    }
                }
                Constants.FacebookNID = string.Empty;
                Constants.TwitterScreenName = string.Empty;
                Constants.BlogAddress = string.Empty;
                Constants.personid = 0;
                NavigationService.GoBack();
                AppSettings.BackgroundAgenError = "btnsave_click1 Method in AddCast.xaml.cs completed successfully..!!!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at btnsave_click1 Method in AddCast.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at btnsave_click1 method in AddCast.xaml.cs file", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            Constants.FacebookNID = string.Empty;
            Constants.TwitterScreenName = string.Empty;
            Constants.BlogAddress = string.Empty;
            helppopup.close();
            helppopup_twit.close();
            helppopup_blog.close();
        }

        private void BloggerImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(TbCelebrity.Text))
                valid.Visibility = Visibility.Visible;
            else
            {
                if (NetworkHelper.IsNetworkAvailableForDownloads())
                {
                    TbId = TbBloggerID;
                    //NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?BlogType=Blogger", UriKind.RelativeOrAbsolute));
                    NavigationService.Navigate(new Uri("/Views/Browser_Blogger.xaml?Parameter=" + TbCelebrity.Text, UriKind.RelativeOrAbsolute));
                }
                else
                    MessageBox.Show("No Network Available...!!!");
            }
        }

        private void TwitterImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(TbCelebrity.Text))
                valid.Visibility = Visibility.Visible;
            else
            {
                if (NetworkHelper.IsNetworkAvailableForDownloads())
                {
                    TbId = TbTwitterID;
                    //NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?BlogType=Twitter", UriKind.RelativeOrAbsolute));
                    NavigationService.Navigate(new Uri("/Views/Browser_Twitter.xaml?Parameter=" + TbCelebrity.Text, UriKind.RelativeOrAbsolute));
                }
                else
                    MessageBox.Show("No Network Available...!!!");
            }
        }

        private void FacebookImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(TbCelebrity.Text))
                valid.Visibility = Visibility.Visible;
            else
            {
                if (NetworkHelper.IsNetworkAvailableForDownloads())
                {
                    TbId = TbFacebookID;
                    //NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?BlogType=FaceBook", UriKind.RelativeOrAbsolute));
                    NavigationService.Navigate(new Uri("/Views/Browser.xaml?Parameter=" + TbCelebrity.Text, UriKind.RelativeOrAbsolute));
                }
                else
                    MessageBox.Show("No Network Available..!!!");
            }
        }

        private void imgTitle_MouseEnter(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void persononlineimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(TbCelebrity.Text))
                valid.Visibility = Visibility.Visible;
            else
            {
                if (NetworkHelper.IsNetworkAvailableForDownloads())
                {
                    //(sender as Image).Source = null;
                    var bingKey = "4Wz8eOfl6WSfFPcyQsxCWBfdMCJq41RvSd1KtoBPVIQ";
                    var authentication = string.Format("{0}:{1}", string.Empty, bingKey);
                    var encodedKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(authentication));
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.datamarket.azure.com/Bing/Search/v1/Image?Query='" + TbCelebrity.Text + "'&ImageFilters=%27Style%3aPhoto%2bSize%3aMedium%2bAspect%3aTall%27&$top=50&$format=Atom");
                    request.Method = "GET";
                    request.Headers["Authorization"] = "Basic " + encodedKey;
                    request.BeginGetResponse(new AsyncCallback(RequestBlogCompleted), request);
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                    });
                }
            }
        }

        private void RequestBlogCompleted(IAsyncResult result)
        {
            var request = (HttpWebRequest)result.AsyncState;
            var response = (HttpWebResponse)request.EndGetResponse(result);
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            string responseStr = responseReader.ReadToEnd();
            Stream strm = new MemoryStream(Encoding.UTF8.GetBytes(responseStr));
            XElement MyXMLConfig = XElement.Load(strm);
            XNamespace atomNS = "http://www.w3.org/2005/Atom";
            XNamespace Img = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            XNamespace met = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
            Constants.OnlineImageUrls = new ObservableCollection<string>(MyXMLConfig.Descendants(atomNS + "entry").Descendants(met + "properties").Elements().Where(i => i.Name == Img + "MediaUrl").Select(i => i.Value).ToList());
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
            });
        }

        private void personlocalimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(TbCelebrity.Text))
                valid.Visibility = Visibility.Visible;
            else
            {
                //(sender as Image).Source = null;
                PhotoChooserTask task = new PhotoChooserTask();
                task.Completed += task_Completed;
                task.Show();
            }
        }

        void task_Completed(object sender, PhotoResult e)
        {
            SamePage = true;
            if (e.TaskResult == TaskResult.OK)
            {
                Constants.UserImage_socialcelebs = new BitmapImage();
                Constants.UserImage_socialcelebs.SetSource(e.ChosenPhoto);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml", UriKind.Relative));
                });
            }
        }

        private void TbCelebrity_TextChanged(object sender, TextChangedEventArgs e)
        {
            valid.Visibility = Visibility.Collapsed;
        }

        private void Image_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            helppopup.ShowPopup();
        }

        private void Image_MouseLeftButtonDown_2(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            helppopup_twit.ShowPopup();
        }

        private void Image_MouseLeftButtonDown_3(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            helppopup_blog.ShowPopup();
        }
    }
}